<template>
  <div class="biz-container">
    <table-layout :haveSider="false">
      <template #searchBox>
        <search-layout
          :formInfos="q_formInfos"
          :formDatas="q_formDatas"
          message="提示 : 注册证需要在“证照管理/供应商证照审核”中先行审核。"
          @onFind="onFind"
        ></search-layout>
      </template>
      <template #batchOperat>
        <batch-operat-btn 
          :addData="false" @onAddData="onAddData"
          :optData="optText" @onOptData="onBatchAudit"
        >
          <template #cusBtn>
            <!-- <a-button type="primary" icon="vertical-align-bottom" size="small"> 自定义按钮 </a-button> -->
            <a-button type="primary"  @click="onAllAudit" >一键审核</a-button>
            <!-- <im-export></im-export> -->
          </template>
        </batch-operat-btn>
      </template>
      <template #tableList="slotData">
        <a-list-table
          :columns="columns"
          :tableData="listdata"
          :pagination="pagination"
          :isSelecttion="true"
          :loading="loading"
          :renderStateByField="renderStateByField"
          :scroll="{y:slotData.tableHeight}"
          @onTableChange="handleTableChange"
          @onselectChange="onselectChange"
          @onAction="onAction"
          :links="links"
          @onTouchlinkCell="onTouchlinkCell"
        >
        </a-list-table>
      </template>
    </table-layout>
     <auditModal  ref="auditModal" @ok="handleModalSaveOk" @close="handleModalCancel" />
     <viewModal ref="viewModal" @ok="handleModalSaveOk" @close="handleModalCancel" />
  </div>
</template>

<script>
import searchLayout from '@/views/app/biz/common/searchLayout'
import batchOperatBtn from '@/views/app/biz/common/batchOperatBtn'
import tableLayout from '@/views/app/biz/common/index'
import aListInfo from '@/views/app/biz/common/aListInfo'
import aListTable from '@/views/app/biz/common/aListTable'
import viewModal from './viewModal'
import auditModal from './auditModal'
import {
  getByConditions,
  getByConditionsCount,
  auditInfo
} from './purchasedgoods'


// 字段列表
const columns = [
  //   { title: '数据有效区域(国、省、市、县、院)', dataIndex: 'areaUse', key: 'areaUse', align: 'center' },
  // { title: '商品自编码', dataIndex: 'code', key: 'code', align: 'center' },
  { title: '标准编码', dataIndex: 'standardCode', key: 'standardCode', align: 'center' },
  { title: '品名', dataIndex: 'productNameZh', key: 'productNameZh', align: 'center',scopedSlots: { customRender: 'productNameZh' } },
//   { title: '英文名称', dataIndex: 'productNameEn', key: 'productNameEn', align: 'center' },
  { title: '通用名', dataIndex: 'commonName', key: 'commonName', align: 'center' },
  { title: '供应商名称', dataIndex: 'supplierOrgName', key: 'supplierOrgName', align: 'center',scopedSlots: { customRender: 'supplierOrgName' } },
  // { title: '一级分类', dataIndex: 'first', key: 'first', align: 'center' },
  // { title: '二级分类', dataIndex: 'second', key: 'second', align: 'center' },
  // { title: '三级分类', dataIndex: 'third', key: 'third', align: 'center' },
  { title: '规格（特征、参数）', dataIndex: 'spec', key: 'spec', align: 'center' },
//   { title: '型号(剂型)', dataIndex: 'model', key: 'model', align: 'center' },
//   { title: '医保代码', dataIndex: 'medicareCode',key: 'medicareCode',   align:'center', },
//   { title: '描述', dataIndex: 'disc', key: 'disc', align: 'center' },
  { title: '品牌', dataIndex: 'brand', key: 'brand', align:'center' },
//   { title: '上市许可持有企业社会编码', dataIndex: 'mahCode', key: 'mahCode', align: 'center' },
//   { title: '上市许可持有企业中文名', dataIndex: 'mahZh', key: 'mahZh',align:'center'  },
//   { title: '上市许可持有企业英文名', dataIndex: 'mahEn', key: 'mahEn', align: 'center' },
//   { title: '生产企业社会编码', dataIndex: 'manufacturerCode', key: 'manufacturerCode', align: 'center' },
  { title: '生产企业名称', dataIndex: 'manufacturerZh', key: 'manufacturerZh',align:'center', scopedSlots: { customRender: 'manufacturerZh' } },
//   { title: '生产企业英文名称', dataIndex: 'manufacturerEn', key: 'manufacturerEn', align: 'center' },
  { title: '产地', dataIndex: 'origin', key: 'origin', align: 'center' },
//   { title: '产品类别(字典medicalCategory)', dataIndex: 'category', key: 'category', align: 'center' },
//   { title: '计量单位', dataIndex: 'measurement', key: 'measurement', align: 'center' },
//   { title: '药品本位码', dataIndex: 'sdc', key: 'sdc', align: 'center' },
//   { title: '当前批准类型(字典medicalApprovalType)', dataIndex: 'approvalType', key: 'approvalType', align: 'center' },
  { title: '注册证号', dataIndex: 'approvalNum', key: 'approvalNum', align: 'center',scopedSlots: { customRender: 'approvalNumlink' }},
  // { title: '厂家证照', dataIndex: 'manufacturerLicense',width: 65, key: 'manufacturerLicense', align: 'center',scopedSlots: { customRender: 'manufacturerLicense' } },
  // { title: '授权书', dataIndex: 'letterAuthorization', width: 65,key: 'letterAuthorization', align: 'center',scopedSlots: { customRender: 'letterAuthorization' } },
//   { title: '当前有效期始', dataIndex: 'approvalDate', key: 'approvalDate', align: 'center' },
  { title: '有效期止', dataIndex: 'validDate', key: 'validDate', align: 'center' },
  { title: '状态', dataIndex: 'state', key: 'state', align: 'center',scopedSlots: { customRender: 'saleGoodsState' } },
  { title: '结算方式', dataIndex: 'settlement', key: 'settlement', align: 'center' },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'operation',
    width: 150,
    align: 'center',
    scopedSlots: { customRender: 'action' },
  },
]
const renderStateByField=['saleGoodsState']
let links=['approvalNumlink','productNameZh','supplierOrgName']

export default {
  components: {
    searchLayout,
    batchOperatBtn,
    tableLayout,
    aListInfo,
    aListTable,
    viewModal,
    auditModal
  },
  data() {
    return {
      columns: columns,
      listdata: [],
      links:links,
      loading: false,
      renderStateByField:renderStateByField,
      pagination: {
        //分页配置
        current: 1, //当前页码 current
        pageSize: 10, //每页显示条数 pageSize
        total: 1,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ['2', '10', '50', '100'],
      },
      // 查询表单
      q_formInfos: [
        { label: '供应商', name: 'supplierOrgPid', type: 'supplier', placeholder: '供应商' },
        { label: '品名', name: 'productNameZh', type: 'input', placeholder: '品名' },
        { label: '规格', name: 'spec', type: 'input', placeholder: '规格' },
        { label: '注册证号',name: 'approvalNum',type: 'input', state:'全部',placeholder: '注册证号'},
        { label: '生产企业名称',name: 'manufacturerZh',type: 'input',placeholder: '生产企业名称'},
        { label: ['查询', '重置'], type: 'botton' }
      ],
      // 查询表单绑定数据
      q_formDatas: {
        productNameZh: null,
        approvalNum: null,
        supplierOrgPid: null,
        manufacturerZh:null,
        spec:null,
      },
      pData: {}, // 条件查询参数
      isJump:false,
      optText: '批量审核',
      selectedRowKeys: [],
      selectedRows: [],
      notAudit: false
    }
  },
  computed: {},
  watch: {
    //监听路由，只要路由有变化(路径，参数等变化)都有执行下面的函数，你可以
    $route: {
        handler: function (val, oldVal) {
          //判断是进入该页面还是离开
          if (this.$route.name=='goods' ) {
            //读取该页面是否缓存，未缓存时：
            if (!this.$route.meta.keepAlive) {
              //读取页面跳转传参
              if(this.$route.params.areaDm){
                this.q_formDatas.areaUse=this.$route.params.areaDm
              }
              this.getTotal()
              this.getList(this.q_formDatas)
            }else{
              console.log(this.$route.params.isBack);
              //已缓存时判断是否是返回
              if (!this.$route.params.isBack) {
                this.getTotal()
                this.getList(this.q_formDatas)
              }
              this.isJump=false
            }
          }
          
        },
        deep: true,
        immediate:true
    }
  },
  beforeRouteEnter(to,from,next){
    console.log('beforeRouteEnter',to,from);
    next(vm=>{
      console.log(vm.isJump);
    });
  },
  beforeRouteLeave(to,from,next){
    if (this.isJump) {
      from.meta.keepAlive=true
    }else{
      from.meta.keepAlive=false
    }
    next();
  },
  mounted(){
    console.log('mounted');
    // this.getTotal()
    // this.getList(this.q_formDatas)
    
  },
  methods: {
    formatParms(){
      let sbdata=JSON.parse(JSON.stringify(this.q_formDatas))
      for (let key in sbdata) {
        // console.log(key,sbdata[key]);
        if (!sbdata[key]){
          sbdata[key]=null  
        }
        if (key=='productNameZh'||key=='manufacturerZh'||key=='spec'||key=='approvalNum') {
          if (sbdata[key]==null) {
            sbdata[key]=`%%`
          }else{
            sbdata[key]=`%${sbdata[key]}%`
          }
          
        }
      }
      return sbdata
    },
    // 初始化页面时得到总数
    async getTotal() {
      let pages = ''
      pages = await getByConditionsCount(this.formatParms())
      console.log(pages)
      if (pages && pages.code && pages.code === 'C1') {
        const pagination = { ...this.pagination }
        pagination.total = pages.data
        this.pagination = pagination
        this.pagination.showTotal =  (showTotal) => {return `共 ${showTotal} 条`}
      }
    },
    // 初始化查询时的数据列表
    async getList(params) {
      console.log('请求列表时传入的数据', this.formatParms())
      let actionBtn=['企业证照',]
      this.loading = true
      let listdata = []
      let res = ''
      res = await getByConditions(this.formatParms(), this.pagination)
      this.loading = false
      console.log(res)
      if (res && res.code && res.code === 'C1' && res.data) {
        const resdata = res.data
         for (let item of resdata) {
            switch (item.state) {
              case '待审核':
                actionBtn = ['审核', '企业证照']
                break
              default:
                actionBtn = ['企业证照']
            }
            listdata.push({
               key: item.pid,
               action:actionBtn ,
               ...item
               }
            )
         }
         this.listdata =listdata
      } else {
        this.listdata = []
      }
      console.log(this.listdata)
    },
    // 新增按钮 点击了新增
    onAddData() {
      
    },
    // 关闭模态详细框
    handleModalCancel() {
    },
    // 模态详细框提交按钮
    handleModalSaveOk() {
      this.getList(this.q_formDatas)
    },
    // 操作按钮
    onAction(text, record, index) {
      if (text == '审核') {
        //审核
        this.$refs.auditModal.editModal(record.pid, null)
      } else if (text == '企业证照') {
        this.isJump=true
        this.$router.push({ 
          name: 'supplierLicense', 
          params: {
            isJump:this.isJump ,
            pathName:this.$route.name,
            suoShupmc: record.supplierOrgName
          } 
        })
      }
    },
    // 触发改变页码,筛选,排序时的回调
    handleTableChange(pagination, filters, sorter) {
      this.pagination.current = pagination.current
      this.pagination.pageSize = pagination.pageSize
      this.getList(this.q_formDatas)
    },
    // 查询按钮
    onFind (){
      this.pagination.current = 1
      this.getTotal()
      this.getList(this.q_formDatas)
    },

    onTouchlinkCell( text, record, index,link){
      console.log(record);
      if(link=='approvalNumlink'){
        this.isJump=true
        this.$router.push({ 
          name: 'registerLicense', 
          params: {
            isJump:this.isJump ,
            pathName:this.$route.name,
            zhengZhaohm: record.approvalNum
          } 
        })
      }else if(link=='productNameZh'){
        this.$refs.viewModal.showModal(record.pid,record)
      }else if(link=='supplierOrgName'){
        this.isJump=true
        this.$router.push({ 
          name: 'supplierInfo', 
          params: {
            isJump:this.isJump ,
            pathName:this.$route.name,
            supplierOrgPid: record.gongYinsOrgPid 
          } 
        })
      }
    },
    // 多选批量操作
    onselectChange(selectedRowKeys, selectedRows) {
      // this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      for (const item of this.selectedRows) {
        if (item.state != '待审核') {
          this.notAudit = true
          return
        } else {
          this.notAudit = false
        }
      }
    },
    onBatchAudit() {
      if (this.selectedRows.length) {
        if (this.notAudit) {
          this.$message.warning({ content: '已选项中含有已审核的记录，请选择待审核的记录', duration: 3 })
        } else {
          this.$refs.auditModal.batchModal(this.selectedRows)
        }
      } else {
        this.$message.warning({ content: '未选择要审核的记录', duration: 3 })
      }
    },
    onAllAudit(){
      this.$refs.auditModal.allModal(this.listdata[0])
    }
  },
}
</script>

<style>
</style>